package util;

import java.io.*;
import java.util.*;

public class FileUtil {

    public static String readFile(String filename) {

        BufferedReader br = null;
        StringBuffer str = new StringBuffer();
        try {
            br = new BufferedReader(new InputStreamReader(getStream(filename)));

            String line;
            while ((line = br.readLine()) != null)
                str.append(line + "\n");

            return str.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            closeStream(br, null);
        }
    }

    public static void initDir(String path) {
        new File(path.replaceAll("\\.", "/")).mkdirs();
    }

    public static void copyFile(HashMap<String, String> params, String originalName, String copyName, String outputPath) {

        outputPath = outputPath.replaceAll("\\.", "/");
        String line;
        BufferedReader br = null;
        PrintWriter pw = null;

        StringBuffer str = new StringBuffer();

        try {
            /* create output file */
            File destFile = new File(outputPath + "/" + copyName);

            if (destFile.exists())
                return;
            else
                destFile.createNewFile();

            /* create streams */
            br = new BufferedReader(new InputStreamReader(getStream(originalName)));
            pw = new PrintWriter(new FileOutputStream(destFile));

            /* read into string */
            while ((line = br.readLine()) != null)
                str.append(line + "\n");
            String stringVal = str.toString();

            /* replace params */
            for (String key : params.keySet())
                stringVal = stringVal.replaceAll(key, params.get(key));

            /* write to output file */
            pw.write(stringVal);

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            closeStream(br, pw);
        }
    }
    
    public static void copyFile(HashMap<String, String> params, String originalName, String outputPath) {
        copyFile(params, originalName,originalName.substring(originalName.lastIndexOf('/') + 1), outputPath);
    }

    private static void closeStream(BufferedReader br, PrintWriter pw) {
        try {
            if (br != null)
                br.close();
            if (pw != null)
                pw.close();
        } catch (IOException ignore) {
        }
    }

    private static InputStream getStream(String filename) {
        return FileUtil.class.getResourceAsStream("/resources/" + filename);
    }
}
